package com.light.mytext.lock

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.light.mytext.R
import com.light.mytext.utiles.ToastUtils
import kotlinx.android.synthetic.main.activity_lovk.*
import kotlinx.android.synthetic.main.activity_my_thread.*
import kotlinx.android.synthetic.main.activity_thread_pool.*
import kotlin.concurrent.thread

/**
 * 同步锁的使用
 */
class LockActivity : AppCompatActivity() {
    var index = ""
    var str =
        arrayOf("你", "好", "呀", "！")
    var stringbuffer: StringBuffer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_lovk)
        init_Listener()

    }

    fun init_Listener() {
        tv_click.setOnClickListener {
            stringbuffer = StringBuffer("")
            stringbuffer!!.append("加锁后,先抢到锁的先执行，一个进程结束后再执行另外一个"+"\r\n")
            val t1: Thread = MyThread()
            val t2: Thread = MyThread()
            t1.start()
            t2.start()
            Thread.sleep(500)
//            Log.i("Lock==", index.toString())
        }
    }

    @Synchronized
    fun add(i: Int) {
        index = str[i]
        Log.i("Lock==", index + Thread.currentThread().name)
        stringbuffer!!.append(index + Thread.currentThread().name)
        stringbuffer!!.append("\r\n")
        tv_text.post {
            tv_text.text = stringbuffer.toString()
        }
    }

    inner class MyThread : Thread() {
        override fun run() {
            super.run()
            for (i in 0..3) {
                add(i)
            }
        }

    }

}